package com.wld.xm.framework.core.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;

public final class JsonUtils {
	private JsonUtils() {
	};

	private static ObjectMapper objectMapper;
	static {
		objectMapper = new JsonObjectMapper();
		objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
		objectMapper.setDateFormat(new SimpleDateFormat("yyyyMMddHHmmss"));
	}

	public static <T> String toJson(T obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static<T> T fromJson(String json,Class<T> cls){
		try{
			return objectMapper.readValue(json, cls);
		}
		catch(IOException e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static <E,T extends Collection<E>> T fromJson(String json,Class<E> cls,Class<T> collectionCls){
		if(com.alibaba.dubbo.common.utils.StringUtils.isBlank(json)) return null;
		JavaType javaType=objectMapper.getTypeFactory().constructParametricType(collectionCls, cls);
		try{
			return objectMapper.readValue(json, javaType);
		}
		catch(IOException e){
			e.printStackTrace();
		}
		return null;
	}
}
